package com.zelin.sellergoods.service.impl;


import com.alibaba.fastjson.JSON;
import com.zelin.dao.TypeTemplateDao;
import com.zelin.entity.SpecificationOptionEntity;
import com.zelin.entity.TypeTemplateEntity;
import com.zelin.sellergoods.service.SpecificationOptionService;
import com.zelin.sellergoods.service.TypeTemplateService;
import com.zelin.utils.PageUtils;
import com.zelin.utils.Query;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.dubbo.config.annotation.Service;
@Service
public class TypeTemplateServiceImpl extends ServiceImpl<TypeTemplateDao, TypeTemplateEntity> implements TypeTemplateService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SpecificationOptionService optionService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TypeTemplateEntity> page = this.page(
                new Query<TypeTemplateEntity>().getPage(params),
                new QueryWrapper<TypeTemplateEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 功能: 以模板id为key，以规格列表及品牌列表为值放到redis中
     * 参数:
     * 返回值: com.zelin.utils.PageUtils
     * 时间: 2021/8/3 14:55
     */
    @Override
    public PageUtils list(Map<String, Object> params) {
        for (TypeTemplateEntity entity : this.list()) {
            //1. 得到模板的品牌字符串
            String brandIds = entity.getBrandIds();
            //2. 将字符串转换为List<Map>
            List<Map> brandMap = JSON.parseArray(brandIds, Map.class);
            //3. 这个品牌列表放到redis中
            redisTemplate.boundHashOps("brandList").put(entity.getId(),brandMap);
            //4. 得到规格字符串
            String specIds = entity.getSpecIds();
            //5. 将规格字符串转换为List<Map>
            List<Map> specMap = JSON.parseArray(specIds, Map.class);
            //6. 对每个规格添加规格选项
            for (Map map : specMap) {
                String id = (String) map.get("id");
                List<SpecificationOptionEntity> options = optionService.list(new QueryWrapper<SpecificationOptionEntity>()
                        .eq("spec_id", id));
                map.put("options",options);
            }
            //7. 将规格列表保存到redis中
            redisTemplate.boundHashOps("specList").put(entity.getId(),specMap);
        }
        return queryPage(params);
    }

}